
import requests
import json
import time
from mytools.qiniu_store import Qiniu_Tool
class Gaode_Map:
    def __init__(self, key='b582711bf3d653f4fc72926275977e17'):
        self.key =key

    #获取ip地址
    def get_poi2(self,keywords,types=160402):
        url = 'https://restapi.amap.com/v3/place/text?parameters'
        params = {
                'key': self.key,
                'keywords':keywords,
                "types":types
                }
        try:
            response = requests.get(url,params=params)

            return self._process_response(response.text)
        except requests.exceptions.RequestException as e:
            return {
                'status': '0',
                'error': f'API请求失败: {str(e)}'
            }


    def _process_response(self, raw_response):
        """处理原始API响应，提取有效信息"""
        try:
            # 将原始API响应转换为JSON格式
            data = json.loads(raw_response)
            # 如果API响应状态不为1，则返回错误信息
            if data.get('status') != '1':
                return {
                    'status': data.get('status', '0'),
                    'error': data.get('info', 'API请求失败')
                }

            processed_pois = []
            # 遍历API响应中的POI信息
            for poi in data.get('pois', []):
                # 提取POI信息，并处理电话号码和照片信息
                processed_poi = {
                    'name': poi.get('name', ''),
                    'address': poi.get('address', ''),
                    'location': poi.get('location', ''),
                    'tel': ', '.join(poi.get('tel', [])) if isinstance(poi.get('tel'), list) else poi.get('tel', ''),
                    'photos': [photo.get('url') for photo in poi.get('photos', []) if photo.get('url')]
                }
                # 将处理后的POI信息添加到列表中
                processed_pois.append(processed_poi)

            # 返回处理后的API响应信息
            return {
                'status': data.get('status'),
                'count': data.get('count'),
                'pois': processed_pois
            }
        except json.JSONDecodeError:
            # 如果解析API响应失败，则返回错误信息
            return {
                'status': '0',
                'error': '解析API响应失败'
            }


    def state_map(self,location):
        # 定义高德地图API请求的URL
        url='https://restapi.amap.com/v3/staticmap?parameters'
        # 定义请求参数
        params= {
            "key":self.key, # 高德地图API密钥
            "zoom":"14", # 缩放级别
            'location': location,
            "size": "800*400",
            "scale": "2",
            "markers": f"mid,0xFF0000,A:{location}"  # 在中心点添加红色标记

        }
        try:
            qiniu_tool = Qiniu_Tool()

            # 发送请求
            response = requests.get(url, params=params)
            # 判断请求是否成功
            if response.status_code == 200:
                timestamp = int(time.time())
                file_name = f"map_{location}_{timestamp}.png"

                # 将图片内容保存到临时文件
                temp_file_path = f"/tmp/{file_name}"
                with open(temp_file_path, 'wb') as f:
                    f.write(response.content)
                # 上传到七牛云
                upload_result = qiniu_tool.qiniu_upload(temp_file_path, file_name)
                # 删除临时文件
                import os
                os.remove(temp_file_path)
                if upload_result['code'] == 10000:
                    # 获取文件URL
                    file_url = qiniu_tool.get_file_url(file_name)
                    return {
                        "code": 10000,
                        "message": "上传成功",
                        "data": {
                            "image_url": file_url,
                            "location": location
                        }
                    }
                else:
                    return {
                        "code": 10001,
                        "message": "图片上传失败",
                        "details": upload_result
                    }
            else:
                print(f"请求失败，状态码: {response.status_code}")
                return False
        except requests.exceptions.RequestException as e:
            # 处理请求异常
            print(f"请求异常: {str(e)}")
            return False
        except Exception as e:
            # 处理其他异常
            print(f"图片显示错误: {str(e)}")
            return False

    def address_code(self,address):
        url='https://restapi.amap.com/v3/geocode/geo?parameters'
        params= {
            'key':self.key,     # 高德地图API密钥
            'address':address,   #地址
        }
        response=requests.get(url,params=params)
        data=json.loads(response.text)
        return data['geocodes'][0]['location']
map = Gaode_Map()


# map.state_map("116.454118,39.935589")
